package com.github.postsanf.yinian.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.bean.ItemDetail;
import com.github.postsanf.yinian.bean.VoiceCardOrder;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.SelectedImg;
import com.github.postsanf.yinian.utils.UIHelper;
import com.github.postsanf.yinian.entity.YNUpTokenResponse;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;

import org.json.JSONObject;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.UUID;

import com.umeng.analytics.MobclickAgent;

public class TimeGoodsJointActivity extends BaseActivity implements View.OnClickListener {
    private ImageView iv_goods_draw;
    private ImageView timegood_back;
    private TextView tv_sure;
    private String goodsPic;
    private UploadManager mUpManager;
    private RelativeLayout rl_bg;
    private ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_time_goods_joint);
        mUpManager = application.getUploadManager();
        String itemID = getIntent().getStringExtra("itemID");
        if (itemID != null) {
            initData();
        } else {
            initView(null);
        }
    }

    private void initData() {
        mProgressDialog = ProgressDialog.show(TimeGoodsJointActivity.this, "", "正在加载中...");
        String itemID = getIntent().getStringExtra("itemID");
        if (itemID == null) {
            showToast("信息加载出错请稍后重试...");
            return;
        }
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_ITEM_ID, itemID);
        StringRequest req = new StringRequest(getString(R.string.SHOP_URL) + getString(R.string.ynGetItemDetail))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        ItemDetail itemDetail = gson.fromJson(s, ItemDetail.class);
                        if (itemDetail.getMsg().equals("success")) {
                            List<String> itemPic = itemDetail.getData().get(0).getItemPic();
                            initView(itemPic.get(0));
                        } else {
                            showToast(itemDetail.getMsg());
                        }
                        mProgressDialog.dismiss();
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                        mProgressDialog.dismiss();
                    }
                });
        liteHttp.executeAsync(req);
    }

    private void initView(String itemPic) {
        goodsPic = getIntent().getStringExtra("goodsPic");
        iv_goods_draw = ((ImageView) findViewById(R.id.iv_goods_draw));
        timegood_back = ((ImageView) findViewById(R.id.timegood_back));
        tv_sure = ((TextView) findViewById(R.id.tv_sure));
        String itemID = getIntent().getStringExtra("itemID");
        if (itemID != null) {
            tv_sure.setVisibility(View.GONE);
            goodsPic = itemPic + "?imageView2/2/w/300";
            Log.d("yuhao", "goodsPic= " + goodsPic);
        } else {
            tv_sure.setVisibility(View.VISIBLE);
        }
        rl_bg = ((RelativeLayout) findViewById(R.id.rl_bg));
        timegood_back.setOnClickListener(this);
        tv_sure.setOnClickListener(this);
        String goodsPicfile = null;
        if (goodsPic != null) {
            if (itemID == null) {
                goodsPicfile = "file://" + goodsPic;
            } else {
                goodsPicfile = goodsPic;
            }
            ImageLoader.getInstance().displayImage(goodsPicfile, iv_goods_draw, new ImageLoadingListener() {
                @Override
                public void onLoadingStarted(String s, View view) {

                }

                @Override
                public void onLoadingFailed(String s, View view, FailReason failReason) {

                }

                @Override
                public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                    int measuredWidth = bitmap.getWidth();
                    int measuredHeight = bitmap.getHeight();
                    float percent = UIHelper.dip2px(TimeGoodsJointActivity.this, 250) * 1.0f / measuredWidth;
                    int height = (int) (percent * measuredHeight);
                    if (height > UIHelper.dip2px(TimeGoodsJointActivity.this, 340)) {
                        height = UIHelper.dip2px(TimeGoodsJointActivity.this, 340);
                    }
                    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(UIHelper.dip2px(TimeGoodsJointActivity.this, 250),
                            height);
                    layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
                    layoutParams.addRule(RelativeLayout.CENTER_VERTICAL);
                    iv_goods_draw.setLayoutParams(layoutParams);
                }

                @Override
                public void onLoadingCancelled(String s, View view) {

                }
            });
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.timegood_back:
                finish();
                break;
            case R.id.tv_sure:
                mProgressDialog = ProgressDialog.show(TimeGoodsJointActivity.this, "", "");
                getToken();
                break;
        }
    }


    private void goToOrder() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        mParam.put(CommonConstants.YNS_GOODS_ID, String.valueOf(MainActivity.goodsid));
        mParam.put(CommonConstants.PICTURE, goodsPic);
        StringRequest req = new StringRequest("https://api.zhuiyinanian.com/YinianProject/eb/AddItem")
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        VoiceCardOrder voiceCardOrder = gson.fromJson(s, VoiceCardOrder.class);
                        if (TextUtils.equals(voiceCardOrder.getMsg(), "success")) {
                            Log.d("yuhao", "success==>" + s.toString());
                            String itemid = voiceCardOrder.getData().get(0).getItemID();
                            String couponPrice = voiceCardOrder.getData().get(0).getCouponPrice();
                            String postage = voiceCardOrder.getData().get(0).getPostage();
                            Intent intent = new Intent(TimeGoodsJointActivity.this, OrderActivity.class);
                            intent.putExtra("couponPrice", couponPrice);
                            intent.putExtra("postage", postage);
                            intent.putExtra("itemid", itemid);
                            intent.putExtra("goodsid", MainActivity.goodsid);
                            startActivity(intent);
                            finish();
                        }
                        mProgressDialog.dismiss();
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        mProgressDialog.dismiss();
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    // 获取上传Token
    private void getToken() {
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynGetUploadToken))
                .setMethod(HttpMethods.Post)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNUpTokenResponse resToken = gson.fromJson(s, YNUpTokenResponse.class);
                        if (ReqUtils.isSuccess(resToken.getCode())) {
                            application.setUpToken(resToken.getData().get(0).getToken());
                            getCoverPicAddress();
                        } else {
                            showToast(resToken.getMsg());
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }


    // 获取七牛云地址
    private void getCoverPicAddress() {
        String prefix = goodsPic.substring(goodsPic.lastIndexOf(".") + 1);
        // 为图片重命名
        String imgName = UUID.randomUUID().toString() + "." + prefix;
        mUpManager.put(goodsPic, imgName, application.getUpToken(),
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        goodsPic = key;
                        Log.d("yuhao", "getCoverPicAddress");
                        goToOrder();
                    }
                }, new UploadOptions(null, null, false, new UpProgressHandler() {
                    public void progress(String key, double percent) {

                    }
                }, null));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SelectedImg.mSelectedImage.clear();
    }

    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
